package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

     @Autowired
    StringRedisTemplate redisTemplate;

     //从reids中获取值
     @ResponseBody
     @GetMapping("/userInfo")
     public String userInfo(@RequestParam("token") String token){
         String s = redisTemplate.opsForValue().get(token);
         return s;
     }

     //返回登入界面
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,
                            Model model,
                            @CookieValue(value="sso_token",required = false) String sso_token){
         //判断 sso_token 是否有待参数
        //  当某个用户登入成功后在认证服务器中 cookie 放入一个 sso_token
        if (!StringUtils.isEmpty(sso_token)){
            //如果有这直接登入
            return "redirect:"+url+"?token="+sso_token;
        }
        model.addAttribute("url",url);
        return "login";
    }


//登入用户密码提交
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username
            , @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
           //判断是否为空
              if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
                  //登录成功跳转，跳回到登录页
                  String replace = UUID.randomUUID().toString().replace("-", "");
                  redisTemplate.opsForValue().set(replace,username);
                  //new 一个Cookie 设置 名为sso_token 值为 随机生成的id
                  Cookie sso_token = new Cookie("sso_token", replace);
                  //  将实例化的cookie 放入 HttpServletResponse 中 将实例化的cookie中
                  response.addCookie(sso_token);
                  System.out.println("redirect:"+url+"?token="+replace);
                  return "redirect:"+url+"?token="+replace;
              }
 //登入失败后

        return null;
    }


















    @ResponseBody
    @GetMapping("tst")
    public String tst(){
        return "测试";
    }

}
